import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //所有的任务列表在这里存储
    list:[],
    //文本框的内容
    inputValue: 'aaa',
    nextId:5,
    viewKey:'all'
  },
  mutations: {
    initList(state,list){
      state.list=list
    },
    //为store中的inputValue赋值
    setInputValue(state,val){
      state.inputValue=val
    },
    //添加列表项
    addItem(state){
      const obj={
        id:state.nextId,
        info:state.inputValue.trim(),
        done:false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    //根据id删除对应的任务
    removeItem(state,id){
      const i =state.list.findIndex(x => x.id === id)
      if(i!==-1){
        state.list.splice(i,1)
      }
    },
    //更改复选框选中状态
    changeDone (state, id) {
      const index = state.list.findIndex(i => i.id === id)
      if (index !== -1) {
        state.list[index].done = !state.list[index].done
      }
    },
    // 清除已完成的任务
    cleanDone (state) {
      state.list = state.list.filter(x => x.done === false)
    },
    // 修改页面上展示列表数据
    changeViewKey (state, key) {
      state.viewKey = key
    }
  },
  
  getters: {
    // 统计未完成的任务条数
    unDoneLength (state) {
      return state.list.filter(x => x.done === false).length
    },
    infoList (state) {
      if (state.viewKey === 'all') {
        return state.list
      } else if (state.viewKey === 'undone') {
        return state.list.filter(x => x.done === false)
      } else if (state.viewKey === 'done') {
        return state.list.filter(x => x.done === true)
      } else {
        return state.list
      }
    }
  },
  actions: {
    getList(context){
      axios.get('/list.json').then(({ data }) =>{
        console.log(data);
        context.commit('initList',data)
      })
    }
  },
  modules: {
  }
})
